package hot_100;

import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class 括号生成 {
    public static void main(String[] args) {

    }

    List<String> ans = new LinkedList<>();
    Deque<Character> deque = new LinkedList<>();

    public List<String> generateParenthesis(int n) {
        Dfs(n, 0);
        return ans;
    }

    public void Dfs(int n, int x) {
        if (n == 0 && x == 0) {
            StringBuilder sb = new StringBuilder();
            for (char c : deque) {
                sb.append(c);
            }
            ans.add(sb.toString());
        }

        if (n > 0) {
            deque.addLast('(');
            Dfs(n - 1, x + 1);
            deque.removeLast();
        }
        if (x > 0) {
            deque.addLast(')');
            Dfs(n, x - 1);
            deque.removeLast();
        }
    }
}
